#ifndef _LOG_HPP
#define _LOG_HPP

#include <iostream>
#include <string>
#include <ctime>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

/*  
 *  日志等级
 *  INFO      1(普通)
 *  WARNING   2(警告)
 *  ERROR     3(错误)
 *  FATAL     4(致命错误)
 */

#define INFO    1
#define WARNING 2
#define ERROR   3
#define FATAL   4

// C语言中#可以将整数转换成字符串
// __FILE__对应文件、__LINE__所在行
#define LOG(level, message) Log(#level, message, __FILE__, __LINE__)

// 参数过多，使用宏
void Log(std::string level, std::string message, std::string file_name, int line)
{
    std::cout << "[" << level << "]" << "[" << time(0) << "]" << "[" << message << "]" << "[" << file_name << "]" << "[" << line << "]" << std::endl; 
    // 写入日志中
    umask(0);
    int fd = open("log.txt", O_WRONLY | O_RDONLY | O_CREAT | O_APPEND, 0777);
    //int fd = open("wwwroot/index.html", O_WRONLY | O_RDONLY | O_APPEND, 0777);
    int back_fd = dup(1);
    dup2(fd, 1);
    std::cout << "[" << level << "]" << "[" << time(0) << "]" << "[" << message << "]" << "[" << file_name << "]" << "[" << line << "]" << std::endl; 
    
    //dup2(1, fd);
    /*  
     *  dup2之后，1就变成了fd的拷贝，所以dup2(fd, 1)仍然是fd
     *  处理方法：使用dup将1提前备份一份
     */
    dup2(back_fd, 1);;
    close(fd);
}

#endif
